1
|
|
|
import { inspect } from 'util'; |
2
|
|
|
import LIVR from 'livr'; |
3
|
|
|
import { assert, AssertionError } from 'chai'; |
4
|
|
|
import { isFunction } from 'myrmidon'; |
5
|
|
|
import dayjs from 'dayjs'; |
6
|
|
|
import factory, { load } from '../Test'; |
7
|
|
|
|
8
|
|
|
load('lib/livr.js'); |
9
|
|
|
|
10
|
|
|
function testLIVR(data, rule, { valid, error } = {}) { |
11
|
|
|
try { |
12
|
|
|
const validator = new LIVR.Validator({ data: rule }); |
13
|
|
|
const validData = validator.validate({ data }); |
14
|
|
|
const errors = validator.getErrors(); |
15
|
|
|
|
16
|
|
|
if (!error) { |
17
|
|
|
assert.notOk(errors, data); |
18
|
|
|
if (isFunction(valid)) return valid(validData.data); |
|
|
|
|
19
|
|
|
assert.ok(validData, data); |
20
|
|
|
assert.deepEqual(validData.data, valid); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
if (error) { |
|
|
|
|
24
|
|
|
assert.ok(errors, data); |
25
|
|
|
assert.notOk(validData, data); |
26
|
|
|
assert.deepEqual(errors.data, error); |
|
|
|
|
27
|
|
|
} |
28
|
|
|
} catch (error_) { |
29
|
|
|
if (!(error_ instanceof AssertionError)) console.log(inspect(error_)); |
|
|
|
|
30
|
|
|
throw error_; |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
suite('Utils: validators #no-pack'); |
35
|
|
|
|
36
|
|
|
before(async function () { |
37
|
|
|
await factory.cleanup(); |
38
|
|
|
}); |
39
|
|
|
|
40
|
|
|
test('Positive: Date', function () { |
41
|
|
|
[ |
42
|
|
|
dayjs().toISOString(), |
43
|
|
|
dayjs(), |
44
|
|
|
dayjs().valueOf(), |
45
|
|
|
dayjs().toDate(), |
46
|
|
|
new Date() |
47
|
|
|
].forEach(inp => |
48
|
|
|
testLIVR(inp, 'date', { valid : out => { |
49
|
|
|
assert.equal(out.toISOString, dayjs(inp).toISOString); |
50
|
|
|
} })); |
51
|
|
|
|
52
|
|
|
[ |
53
|
|
|
null, |
54
|
|
|
undefined, |
55
|
|
|
'' |
56
|
|
|
].forEach(inp => |
57
|
|
|
testLIVR(inp, 'date', { valid : out => { |
58
|
|
|
assert.equal(inp, out); |
59
|
|
|
} })); |
60
|
|
|
}); |
61
|
|
|
|
62
|
|
|
test('Negative: Date', function () { |
63
|
|
|
[ |
64
|
|
|
'date', |
65
|
|
|
'15.03', |
66
|
|
|
'26.05.2007' |
67
|
|
|
].forEach(inp => |
68
|
|
|
testLIVR(inp, 'date', { error: 'WRONG_DATE' })); |
69
|
|
|
}); |
70
|
|
|
|
Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.
Consider:
If you or someone else later decides to put another statement in, only the first statement will be executed.
In this case the statement
b = 42
will always be executed, while the logging statement will be executed conditionally.ensures that the proper code will be executed conditionally no matter how many statements are added or removed.